//
//  SCPhotoPickerView.swift
//  weibo
//
//  Created by 阿城 on 15/12/14.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

class SCPhotoPickerView: UICollectionView {
    
    var imageList = [UIImage](){
        didSet{
            self.hidden = imageList.count == 0
        }
    }
    
    var addImageBackclosrue: (()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        hidden = true
        
        //设置间隔
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumInteritemSpacing = kMargin / 2
        layout.minimumLineSpacing = kMargin / 2
        
        dataSource = self
        delegate = self
        
        //注册
        registerClass(SCPhotoCell.self, forCellWithReuseIdentifier: "cell")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置cell
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        let cellW: CGFloat = CGFloat(Int(width - kMargin) / 3)
        layout.itemSize = CGSize(width: cellW, height: cellW)
    }
    
    func addImage(image: UIImage){
        if imageList.count < 9{
            imageList.append(image)
            reloadData()
        }
    }
    
}

extension SCPhotoPickerView: UICollectionViewDataSource, UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let num = imageList.count
        return num == 0||num == 9 ? num : num + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! SCPhotoCell
        
        //辨别加号按钮
        if indexPath.row != imageList.count{
            cell.image = imageList[indexPath.row]
            cell.deleteBtnBackclosure = {[weak self] in
                self?.imageList.removeAtIndex(indexPath.row)
                self?.reloadData()
            }
        }else{
            cell.image = nil
        }
        
        return cell
    }
    
    //cell的选择监听
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //点击加号
        if indexPath.row == imageList.count && imageList.count != 9{
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
            addImageBackclosrue?()
        }
    }
    
}


class SCPhotoCell: UICollectionViewCell{
    var image: UIImage?{
        didSet{
            
            if image != nil {
                imgView.image = image
                imgView.highlightedImage = nil
            }else{
                imgView.image = UIImage(named: "compose_pic_add")
                imgView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            }
            
            deleteBtn.hidden = image == nil
        }
    }
    
    var deleteBtnBackclosure : (()->())?
    
    private lazy var imgView: UIImageView = UIImageView()
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        btn.sizeToFit()
        btn.addTarget(self, action: "deleteBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        addSubview(imgView)
        addSubview(deleteBtn)
        
        imgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(self)
            make.top.equalTo(self)
        }
    }
    
    @objc private func deleteBtnClick(){
        deleteBtnBackclosure?()
    }
    
}
